package com.kjsdfgk.hjmdsf.ftvdolist.mvp.presenter;

import android.app.Application;
import android.util.Base64;

import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;
import timber.log.Timber;

import javax.inject.Inject;

import com.jess.arms.utils.RxLifecycleUtils;
import com.kjsdfgk.hjmdsf.app.App;
import com.kjsdfgk.hjmdsf.app.entity.Account;
import com.kjsdfgk.hjmdsf.app.entity.ListBean;
import com.kjsdfgk.hjmdsf.app.entity.WebPhoto;
import com.kjsdfgk.hjmdsf.app.entity.XJVideoJson;
import com.kjsdfgk.hjmdsf.ftvdolist.mvp.bean.XJResult;
import com.kjsdfgk.hjmdsf.ftvdolist.mvp.contract.VdoListContract;
import com.kjsdfgk.hjmdsf.live.mvp.bean.ResultLive;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Element;
import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 04/30/2020 18:02
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@FragmentScope
public class VdoListPresenter extends BasePresenter<VdoListContract.Model, VdoListContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public VdoListPresenter(VdoListContract.Model model, VdoListContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    int page = 2;
    public void typeSearch(String typeValue  ) {
        {
            String uid="8517369";

            String limit="20";
            String vod_big_class = typeValue;
            if ("最新片源".equals(typeValue)){
                vod_big_class="全部";
            }

//       String vod_big_class="高清无码";
            String vod_lang="全部";

            String vod_source="全部";
            String vod_year="全部";
            String vod_actor_class="全部";
            String vod_class="最新片源";
            String vod_area="全部";

            String vod_type="全部";
            String big_vod_class="全部";
            page = 2;
            mModel.typeSearch(uid,1,limit,vod_big_class,vod_lang,
                    vod_source,vod_year,vod_actor_class,vod_class,vod_area,
                    vod_type,big_vod_class)
                    .subscribeOn(Schedulers.io())
                    .retryWhen(new RetryWithDelay(3, 2))
                    .doOnSubscribe(disposable -> mRootView.showLoading(new Date().toString()))
                    .subscribeOn(AndroidSchedulers.mainThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                    .subscribe(new ErrorHandleSubscriber<XJVideoJson>(mErrorHandler) {
                        @Override
                        public void onError(@NonNull Throwable e) {
                            mRootView.hideLoading();
                            mRootView.showMessage("服务器繁忙 ，请稍后在试！");
                        }
                        @Override
                        public void onNext(@NonNull XJVideoJson result) {
                                mRootView.hideLoading();
                                mRootView.showTypeSearch(result.getList());
                        }
                    });
        }

    }


    public void loadVideoListData(String typeValue) {
        String uid="8517369";

        String limit="20";
        String vod_big_class = typeValue;
        if ("最新片源".equals(typeValue)){
            vod_big_class="全部";
        }

//       String vod_big_class="高清无码";
        String vod_lang="全部";

        String vod_source="全部";
        String vod_year="全部";
        String vod_actor_class="全部";
        String vod_class="最新片源";
        String vod_area="全部";

        String vod_type="全部";
        String big_vod_class="全部";

        final String key = new Date().toString();
        mModel.typeSearch(uid,page,limit,vod_big_class,vod_lang,
                vod_source,vod_year,vod_actor_class,vod_class,vod_area,
                vod_type,big_vod_class)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(3, 2))
                .doOnSubscribe(disposable -> mRootView.showLoading(key))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<XJVideoJson>(mErrorHandler) {
                    @Override
                    public void onError(@NonNull Throwable e) {

                        mRootView.hideLoading();
                        mRootView.showMessage("服务器繁忙 ，请稍后在试！");

                    }

                    @Override
                    public void onNext(@NonNull XJVideoJson result) {
                        mRootView.hideLoading();
                        mRootView.showLoadMore(result.getList());

                    }
                });
    }

    public Account getAccount() {
        return (Account) ((App)mApplication).getAppComponent().extras().get("Account");
    }

    public void ccyySearch(String typeValue) {
        String ccHost ="http://" +  new String(Base64.decode(ccHostMiWen.getBytes(), Base64.DEFAULT));
        switch (typeValue){
            case "最新片源":
            {
                String   url =ccHost+"/";//
                ccyyZXPYSearch(url ,typeValue);
            }

                break;
            case "高清无码":
            {
                String   url =ccHost+"/type/2.html";//
                ccyyZXPYSearch(url,typeValue);
                url =ccHost+"/type/6.html";//
                ccyyZXPYSearch(url,typeValue);
            }

            break;
            case "偷拍自拍":
            {
                String url = ccHost+"/type/1.html";
                ccyyZXPYSearch(url, typeValue);
            }

                break;

            case "日韩女优":
            {
                String url = ccHost+"/type/3.html";
                ccyyZXPYSearch(url, typeValue);
            }
            break;
            case "欧美激情":
            {
                String url = ccHost+"/type/4.html";
                ccyyZXPYSearch(url, typeValue);
            }
            break;
            case "成人动漫":
            {
                String url = ccHost+"/type/5.html";
                ccyyZXPYSearch(url, typeValue);
            }
            break;
            case "今日网红":

                break;

        }
    }
    public void hsck7Search(String typeValue) {
        String hsHost = "http://" + new String(Base64.decode(hsck7MW.getBytes(), Base64.DEFAULT));
        switch (typeValue){
            case "最新片源":
            {
                String   url =hsHost+"/";//
                hsckZXPYSearch(url);
            }

            break;
            case "高清无码":
            {

                String   url =hsHost+"/vodtype/9.html";//
                hsckZXPYSearch(url);

            }

            break;
            case "偷拍自拍":
            {
                String url = hsHost+"/vodtype/2.html";
                hsckZXPYSearch(url);

            }

            break;

            case "日韩女优":
            {
                String url = hsHost+"/type/3.html";
                ccyyZXPYSearch(url, typeValue);
            }
            break;
            case "欧美激情":
            {
                String url = hsHost+"/type/4.html";
                ccyyZXPYSearch(url, typeValue);
            }
            break;
            case "成人动漫":
            {
                String url = hsHost+"/type/5.html";
                ccyyZXPYSearch(url , typeValue);
            }
            break;
            case "今日网红":

                break;

        }
    }
    private void hsckZXPYSearch(String url ) {
        mModel.ccyyHtml(url)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(3, 2))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<String>(mErrorHandler) {
                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onNext(@NonNull String result) {
                        List<ListBean> list = parseHsck7(result);
                        mRootView.showCcyyHtml( list   );
                        Timber.d(url+"页数据----->");
                    }
                });
    }
    private void ccyyZXPYSearch(String url ,String clazz) {

        mModel.ccyyHtml(url)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(3, 2))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<String>(mErrorHandler) {
                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onNext(@NonNull String result) {
                        mRootView.hideLoading();
                        List<ListBean> list = parseCCYYHtml(result ,clazz);
                        mRootView.showCcyyHtml( list   );
                        Timber.d(url+"页数据----->");
                    }
                });

    }



    final String ccHostMiWen = "NTIwMjAxLmNvbQ==";
    final String hsck7MW = "aHNjazcuY29t";
    public void loadCCListData(String typeValue) {
        String ccHost ="http://" +  new String(Base64.decode(ccHostMiWen.getBytes(), Base64.DEFAULT));
        String hsHost ="http://" +  new String(Base64.decode(hsck7MW.getBytes(), Base64.DEFAULT));
        List<String> urls = new ArrayList<>();
        String   url = "";
        switch (typeValue){
            case "高清无码":
            {
                url =ccHost;
                url = url + "/type/2-"+(page)+".html";
                urls.add(url);

                url =ccHost;
                url = url + "/type/6-"+(page)+".html";
                urls.add(url);

                url =hsHost;
                url = url + "/vodtype/9-"+(page)+".html";
                urls.add(url);
            }
            break;
            case "偷拍自拍":
            {
                url =ccHost;
                url = url + "/type/1-"+(page)+".html";
                urls.add(url);

                url =hsHost;
                url = url + "/vodtype/2-"+(page)+".html";
                urls.add(url);
            }
                break;
            case "日韩女优":
            {
                url =ccHost;
                url = url + "/type/3-"+(page)+".html";
                urls.add(url);
            }
            break;
            case "欧美激情":
            {
                url =ccHost;
                url = url + "/type/4-"+(page)+".html";
                urls.add(url);
            }
                break;
            case "成人动漫":
            {
                url =ccHost;
                url = url + "/type/5-"+(page)+".html";
                urls.add(url);
            }

            break;

        }

        for (String myurl : urls){
            mModel.ccyyHtml(myurl)
                    .subscribeOn(Schedulers.io())
                    .retryWhen(new RetryWithDelay(3, 2))
                    .subscribeOn(AndroidSchedulers.mainThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                    .subscribe(new ErrorHandleSubscriber<String>(mErrorHandler) {
                        @Override
                        public void onError(@NonNull Throwable e) {


                        }

                        @Override
                        public void onNext(@NonNull String result) {
                            mRootView.hideLoading();
                            List<ListBean> list = myurl.contains("520201")? parseCCYYHtml(result,typeValue):parseHsck7(result);
                            mRootView.showLoadMore(  list );
                            Timber.d(myurl + "页数据----->");
                        }
                    });
        }

        page = page +1;
    }


    private List<ListBean> parseHsck7(String result ) {
        String hsck7 = "http://" + new String(Base64.decode(hsck7MW.getBytes(), Base64.DEFAULT));
        List<ListBean> listBeans = new ArrayList<>();
        for (Element element:Jsoup.parse(result).getAllElements().select("div")) {
            if (element.attr("class").equals("stui-vodlist__box")){
                System.out.println(element);
                ListBean bean = new ListBean();
                bean.setVod_name(element.childNode(1).attr("title"));
                bean.setVod_pic(element.childNode(1).attr("data-original"));
                bean.setVod_tag(hsck7 + element.childNode(1).attributes().get("href"));
                bean.setVod_score("8.0");
                bean.setType_id(2200);
                bean.setVod_time((int)(System.currentTimeMillis()/1000L));
                listBeans.add(bean);
            }
        }
        saveHsakldData(listBeans );
        return listBeans;
    }
    private List<ListBean> parseCCYYHtml(String result ,String clazz) {
        String ccHost = "http://" + new String(Base64.decode(ccHostMiWen.getBytes(), Base64.DEFAULT));
        try {
            List<ListBean> listBeans = new ArrayList<>();
            for (Element element : Jsoup.parse(result).getAllElements().select("li")){

                element.child(1).attributes().get("title");



                ListBean bean = new ListBean();
                bean.setVod_name(element.childNode(1).attributes().get("title"));
                bean.setVod_pic(element.childNode(1).childNode(1).attr("data-original"));
                bean.setVod_tag(ccHost + element.childNode(1).attributes().get("href"));
                bean.setVod_score("8.0");
                bean.setType_id(2100);
                bean.setVod_time((int)(System.currentTimeMillis()/1000L));
                bean.setType(clazz);
                bean.setVersion(100);
                listBeans.add(bean);

            }
//            saveHsakldData(listBeans );
            return listBeans;
        }catch (Exception e){
            mRootView.showMessage(e.toString());
        }
        return null;
    }

    private void saveHsakldData(List<ListBean> list) {

        for (ListBean b :list) {
            b.setVod_time((int) (System.currentTimeMillis()/1000));
            List<ListBean> itemList = LitePal.where("vod_tag=?",b.getVod_tag()).find(ListBean.class);
            for (ListBean item : itemList){
                item.delete();
            }
            b.delete();
            b.save();
        }
    }


}
